package com.simple.util.poi;

import com.opencsv.CSVReader;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @program: simple_tools
 * @description: Csv文件读取
 * @author: Mr.chen
 * @create: 2020-04-29 13:53
 **/
public class CsvUtil<T> {

    public List<T> read(String filePath, Class<T> clazz) {
        try {
            CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8));
            HeaderColumnNameMappingStrategy<T> mapper = new HeaderColumnNameMappingStrategy<>();
            mapper.setType(clazz);
            return new CsvToBeanBuilder<T>(reader)
                    .withMappingStrategy(mapper)
                    .build()
                    .parse();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(String.format("csv文件: {%s} 读取异常", filePath));
        }
        return null;
    }
}
